package com.ld.controller;

import com.ld.annotation.LdPermission;
import com.ld.doamin.Employee;
import com.ld.doamin.PageListQuery;
import com.ld.service.IEmployeeService;
import com.ld.basic.utils.AjaxResult;
import com.ld.basic.utils.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
@LdPermission(name = "员工查询",desc = "员工的增删改")
public class EmployeeController {

    @Autowired
    private IEmployeeService service;

    /**
     * 结合部门前端页面查询部门经理
     * @return
     */
    @GetMapping("/dept")
    public AjaxResult getAll(){
      List<Employee> employeelist = service.loadAll();

      return AjaxResult.me().setData(employeelist);
    }

    /**
     * 员工分页查询加高级查询
     * @return
     */
    @PostMapping
    @LdPermission(name="分页查询",desc = "高级查询和分页")
    public AjaxResult pageList(@RequestBody PageListQuery query){
      PageList<Employee> employeePageList = service.queryPage(query);
      return AjaxResult.me().setData(employeePageList);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @LdPermission(name="按id删除员工",desc = "删除指定员工")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            service.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("后端代码异常:"+e.getMessage());
        }
    }

    @PatchMapping
    public AjaxResult deletePatch(@RequestBody List<Long> ids){
        try {
            service.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("后端代码异常:"+e.getMessage());
        }
    }

    /**
     * 保存 (新增或者修改)
     * @param employee
     * @return
     */
    @PutMapping
    public AjaxResult save(@RequestBody Employee employee){
        try {
            if (employee.getId()==null){
                service.insert(employee);
            }else {
                service.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("后端代码异常:"+e.getMessage());
        }
    }


}
